﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace WpfWordsLearner.ViewModels
{
	public class WordsSelectorViewModel : ViewModels.BaseViewModel, IDisposable
	{
		private WpfWordsLearner.WordsSplitter m_spliter = null;

		public WordsSelectorViewModel()
			: base()
		{
			m_spliter = new WordsSplitter();
			WordsToSave = new ObservableCollection<string>();
		}

		private List<string> myVar;
		public List<string> Words
		{
			get { return myVar; }
			set { myVar = value; OnPropertyChanged(() => Words); }
		}

		private ObservableCollection<string> wordsToSave;
		public ObservableCollection<string> WordsToSave
		{
			get { return wordsToSave; }
			set { wordsToSave = value; OnPropertyChanged(() => WordsToSave); }
		}

		private string fNAme;
		public string FileName
		{
			get { return fNAme; }
			set { fNAme = value; OnPropertyChanged(() => FileName); }
		}

		private string fNAme2;
		public string FileName2
		{
			get { return fNAme2; }
			set { fNAme2 = value; OnPropertyChanged(() => FileName2); }
		}

		private string selWord;

		public string SelectedWord
		{
			get { return selWord; }
			set { selWord = value; OnPropertyChanged(() => SelectedWord); }
		}

		public System.Windows.Input.ICommand GetWordsCommand { get { return new WpfWordsLearner.Helper.BaseCommand(GetWords); } }
		private void GetWords()
		{

			if (string.IsNullOrEmpty(FileName))
			{
				Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();

				ofd.Filter = "All files (*.*)|*.*";
				if (ofd.ShowDialog() == true)
				{
					FileName = ofd.FileName;
					m_spliter.SetData(System.IO.File.ReadAllText(FileName));
					Words = m_spliter.SplitByWords();
					Words.Sort(StringComparer.OrdinalIgnoreCase);
				}
			}
			else
			{
				m_spliter.SetData(System.IO.File.ReadAllText(FileName));
				Words = m_spliter.SplitByWords();
				Words.Sort(StringComparer.OrdinalIgnoreCase);
			}
		}

		public System.Windows.Input.ICommand SaveWordsCommand { get { return new WpfWordsLearner.Helper.BaseCommand(SaveWords); } }
		private void SaveWords()
		{
			using (var sw = new System.IO.StreamWriter(FileName2))
			{
				foreach (string word in WordsToSave)
				{
					sw.WriteLine(word);
				}
				sw.Flush();
			}
		}

		public System.Windows.Input.ICommand MoveCommand { get { return new WpfWordsLearner.Helper.BaseCommand(Move); } }
		private void Move()
		{
			WordsToSave.Add(SelectedWord);
		}

		public void Dispose()
		{
			m_spliter.Dispose();
		}
	}
}
